﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyX.Provider
{
    internal class ServiceLocator
    {
        public static void Register<T>(string key, IProvider provider)
        {
            var realKey = SearchKey(key, typeof(T));
            if (realKey == null)
                _providers[new ServiceLocatorKey(key, typeof(T))] = provider;
            else
                _providers[realKey] = provider;
        }

        public static void Register<T>(IProvider provider)
        {
            var realKey = SearchKey(null, typeof(T));
            if (realKey == null)
                _providers[new ServiceLocatorKey(null, typeof(T))] = provider;
            else
                _providers[realKey] = provider;
        }

        public static T Get<T>(string key)
        {
            var realKey = SearchKey(key, typeof(T));
            var provider = _providers[realKey];
            return provider.Get<T>();
        }

        public static T Get<T>()
        {
            return Get<T>(null);
        }

        private static ServiceLocatorKey SearchKey(string key, Type type)
        {
            return (from p in _providers.Keys where p.ServiceKey == key && p.ServiceType == type select p).SingleOrDefault();

        }

        private static Dictionary<ServiceLocatorKey, IProvider> _providers = new Dictionary<ServiceLocatorKey, IProvider>();
    }

    internal class ServiceLocatorKey
    {
        public ServiceLocatorKey(string key, Type serviceType)
        {
            ServiceKey = key;
            ServiceType = serviceType;
        }

        public string ServiceKey { get; private set; }
        public Type ServiceType { get; private set; }
    }
}
